package com.tanglon.filter;

import com.alibaba.fastjson.JSON;
import com.tanglon.constants.AdminConstants;
import com.tanglon.domain.ResponseResult;
import com.tanglon.domain.entity.LoginUser;
import com.tanglon.enums.AppHttpCodeEnum;
import com.tanglon.utils.JwtUtil;
import com.tanglon.utils.RedisCache;
import com.tanglon.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.tanglon.constants.SystemConstants.BLOG_LOGIN;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = request.getHeader("token");

        if(!StringUtils.hasText(token)){
            //该接口不需要登录，放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token拿到userId
        Claims claims= null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时，token非法
            //告知前端需要重新登陆
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
            return;
        }
        String userId = claims.getSubject();

        //去redis找管理员信息根据ADMIN_LOGIN+userId
        LoginUser loginUser = redisCache.getCacheObject(AdminConstants.ADMIN_LOGIN + userId);

        if(Objects.isNull(loginUser)){
            //登录过期，提示重新登陆
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
            return;
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}
